package orm

import "fmt"

/**
 * 使用元数据描述直接描述持久化对象的参数，而不是通过反射获取
 */
type SetMeta struct {
	QueryBody string
	CondAppendMode CondAppendMode
}

type ColumnMeta struct {
	Name string
	Table string
	Column string
	Expr string
}

func (c ColumnMeta) UseAlias() bool {
	return c.Expr != "" || c.Column != ""
}

func (c ColumnMeta) NameExpr() string {
	return fmt.Sprintf("`%s`", c.Name)
}

// 当不使用别名时，返回空字符串
func (c ColumnMeta) OriginExpr() string {
	if c.Expr != "" {
		return c.Expr
	}
	if c.Column == "" {
		return ""
	}
	if c.Table == "" {
		return fmt.Sprintf("`%s`", c.Column)
	} else {
		return fmt.Sprintf("`%s`.`%s`", c.Table, c.Column)
	}
}

/**
 * 以下是一个例子
 */
type TestDataSet struct {
	AName string
	BName string
}

func (TestDataSet) Meta() interface{} {
	return TestDataSetMeta
}


var TestDataSetMeta = struct {
	SetMeta
	AName ColumnMeta
	BName ColumnMeta
}{
	SetMeta{
		QueryBody:"`orm_test_set_a` AS `a` JOIN `orm_test_set_b` AS `b` ON `b`.`aid` = `a`.`id`",
		CondAppendMode:Where,
	},
	ColumnMeta{Name: "a_name", Table:"a", Column:"name"},
	ColumnMeta{Name: "b_name", Table:"b", Column:"name"},
}

func Test()  {
	query := fmt.Sprintf("SELECT count(*) FROM %s", TestDataSetMeta.QueryBody)
	fmt.Println(query)
}

type DefaultSetMeta struct{
	SetMeta
	ColumnList []ColumnMeta
}

func GetDefaultSetMeta(m interface{}) DefaultSetMeta {
	// 通过反射转换成标准的元数据
	_m := m.(struct {
		SetMeta
		AName ColumnMeta
		BName ColumnMeta
	})
	return DefaultSetMeta{
		SetMeta:    _m.SetMeta,
		ColumnList: []ColumnMeta{
			_m.AName,
			_m.BName,
		},
	}
}